package com.hemaapp.yjnh.adapter;

import android.content.Context;
import android.content.Intent;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.hemaapp.yjnh.BaseApplication;
import com.hemaapp.yjnh.BaseUtil;
import com.hemaapp.yjnh.R;
import com.hemaapp.yjnh.listener.OrderItemClickListener;
import com.hemaapp.yjnh.bean.Order;
import com.hemaapp.yjnh.utils.ImageUtils;

import java.util.ArrayList;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * 类描述：买家普通订单和定制订单适配器
 * 创建人：GuiyouZhang
 * 创建时间：2016/7/20 17:22
 * 修改备注：
 */
public class OrderListAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

    private ArrayList<Order> datas;
    private Context mContext;
    private OrderItemClickListener clickListener;

    public OrderListAdapter(Context context, ArrayList<Order> orders, OrderItemClickListener clickListener) {
        this.mContext = context;
        this.datas = orders;
        this.clickListener = clickListener;
    }

    @Override
    public int getItemViewType(int position) {
        if (datas.size() == 0)
            return -1;
        else
            return 0;
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        if (viewType == -1) {
            View itemView = LayoutInflater.from(mContext).inflate(R.layout.listitem_empty_base, parent, false);
            return new EmptyViewHolder(itemView);
        } else {
            View itemView = LayoutInflater.from(mContext).inflate(R.layout.item_order, parent, false);
            return new ViewHolder(itemView);
        }
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
        if (datas.size() == 0) {
            if (holder instanceof EmptyViewHolder)
                ((EmptyViewHolder) holder).tvEmtpy.setText("暂时没有订单");
        } else {
            if (holder instanceof ViewHolder) {
                ((ViewHolder) holder).setDatas(position);
            }
        }
    }

    @Override
    public int getItemCount() {
        return datas.size() == 0 ? 1 : datas.size();
    }

    class ViewHolder extends RecyclerView.ViewHolder {
        @Bind(R.id.tv_order_num)
        TextView tvOrderNum;
        @Bind(R.id.tv_status)
        TextView tvStatus;
        @Bind(R.id.layout_goods)
        LinearLayout layoutGoods;
        @Bind(R.id.tv_freight)
        TextView tvFreight;
        @Bind(R.id.tv_total_fee)
        TextView tvTotalFee;
        @Bind(R.id.div_line)
        View divLine;
        @Bind(R.id.tv_cancel)
        TextView tvCancel;
        @Bind(R.id.tv_confirm)
        TextView tvConfirm;
        @Bind(R.id.tv_friend_pay)
        TextView tvFriendPay;
        @Bind(R.id.tv_pay)
        TextView tvPay;
        @Bind(R.id.tv_send)
        TextView tvSend;
        @Bind(R.id.tv_refuse)
        TextView tvRefuse;
        @Bind(R.id.tv_hint)
        TextView tvHint;
        @Bind(R.id.tv_commit)
        TextView tvCommit;
        @Bind(R.id.tv_aftersale)
        TextView tvAftersale;
        @Bind(R.id.layout_bottom)
        LinearLayout layoutBottom;

        int position = -1;

        ViewHolder(View view) {
            super(view);
            ButterKnife.bind(this, view);
            view.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (clickListener != null && position != -1)
                        clickListener.onItemClickListener(position);
                }
            });
            tvCancel.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    if (clickListener != null)
                        clickListener.onCancel(position);
                }
            });
            tvRefuse.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (clickListener != null)
                        clickListener.onRefusePay(position);
                }
            });
            tvPay.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (clickListener != null)
                        clickListener.onPay(position);
                }
            });
            tvFriendPay.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (clickListener != null)
                        clickListener.onPayBehalf(position);
                }
            });
            tvConfirm.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (clickListener != null)
                        clickListener.onReceive(position);
                }
            });
        }

        public void setDatas(int position) {
            this.position = position;
            Order order = datas.get(position);
            //根据订单状态来显示下方的操作按钮
            tvOrderNum.setText("订单号：" + order.getBill_sn());
            tvStatus.setText(getTradeStatus(order));
            tvFreight.setText("(含运费¥" + order.getShipping_fee() + ")");
            tvTotalFee.setText(order.getTotal_fee());

            //动态添加多个商品
            if (layoutGoods.getChildCount() != 0) {
                layoutGoods.removeAllViews();
            }
            for (int i = 0; i < order.getChildren().size(); i++) {
                View view = LayoutInflater.from(mContext).inflate(
                        R.layout.item_order_goods, null);
                ItemViewHolder ivHolder = new ItemViewHolder();
                itemFindView(view, ivHolder);
                setItem(position, this, i, order, view, ivHolder);
                Order.BillChild child = order.getChildren().get(i);
                //点击商品，进入商品详情,2016.10.12
                view.setTag(child);
                view.setOnClickListener(new View.OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        Order.BillChild child1 = (Order.BillChild) v.getTag();
                        // 先根据商品属性，进入不同的商品详情
                        Intent intent = BaseUtil.createBlogIntent(mContext, child1.getType());
                        intent.putExtra("blog_id", child1.getBlog_id());
                        mContext.startActivity(intent);
                    }
                });
//                //只有问题订单才可以点击，否则把点击事件交还给父控件
//                String itemType = child.getItemtype();//状态	0正常 1申请中 2等待买家发货 3拒绝 4退货中 5退货完成
//                if (!itemType.equals("0")) {//没有退货,或者退货失败
//                    view.setTag(child);
//                    view.setOnClickListener(new View.OnClickListener() {
//
//                        @Override
//                        public void onClick(View v) {
//                            Order.BillChild child1 = (Order.BillChild) v.getTag();
//                            //进入售后详情
//                            Intent itAfter = new Intent(mContext, AfterSalesDetailActivity.class);
//                            itAfter.putExtra("order_id", child1.getId());
//                            itAfter.putExtra("isSeller", false);
//                            mContext.startActivity(itAfter);
//                        }
//                    });
//                }
            }
        }

        /**
         * 获取订单的状态
         *
         * @param order
         * @return
         */
        private String getTradeStatus(Order order) {
            if (order.getStatetype().equals("2")) {
                setBottomButton(new int[]{View.GONE, View.GONE, View.GONE, View.GONE, View.GONE, View.GONE});
                return "已关闭";
            }
            if (order.getReturnflag().equals("1")) {//有退货
                //状态:0正常;1申请中;2等待买家发货;3拒绝;4退货中;5退货完成
                //
                for (Order.BillChild item : order.getChildren()) {
                    int returnSucCount = 0;
                    //计算退货成功的商品数量
                    //2016.11.03 start 客户要求只要发生了退货，就进行问题订单判断
//                    if (item.getItemtype().equals("5")) {
                    if (!item.getItemtype().equals("0")) {
                        returnSucCount++;
                    }
                    //2016.11.03 end 客户要求只要发生了退货，就进行问题订单判断
                    if (returnSucCount == order.getChildren().size()) {//如果全部退货成功,那么就结束，否则按正常逻辑判断
                        setBottomButton(new int[]{View.GONE, View.GONE, View.GONE, View.GONE, View.GONE, View.GONE});
                        return "问题订单";
                    }
                }
            }
            if (!order.getClient_id().equals(BaseApplication.getInstance().getUser().getId())) {//别人请我帮忙代付
                //0非代付;1待确认;2接受代付;3拒绝代付
                if (order.getOther_payflag().equals("1")) {//显示“拒绝”，“支付”
                    setBottomButton(new int[]{View.VISIBLE, View.GONE, View.GONE, View.VISIBLE, View.VISIBLE, View.GONE});
                    return "代付订单";
                } else if (order.getOther_payflag().equals("2")) {
                    setBottomButton(new int[]{View.GONE, View.GONE, View.GONE, View.GONE, View.GONE, View.GONE});
                    return "代付成功";
                } else if (order.getOther_payflag().equals("3")) {
                    setBottomButton(new int[]{View.GONE, View.GONE, View.GONE, View.GONE, View.GONE, View.GONE});
                    return "代付已拒绝";
                } else {
                    setBottomButton(new int[]{View.GONE, View.GONE, View.GONE, View.GONE, View.GONE, View.GONE});
                    return "未知状态";
                }
            }else {
                //交易状态	0 未付款 1: 已付款待发货 2 待收货 3 已收货待评价 4 已评价交易成功
                if (order.getTradetype().equals("0")) {
                    if (order.getOther_payflag().equals("1")) {
                        setBottomButton(new int[]{View.GONE, View.GONE, View.GONE, View.GONE, View.GONE, View.GONE});
                        return "代付中";
                    } else if (order.getOther_payflag().equals("3")) {
                        setBottomButton(new int[]{View.VISIBLE, View.VISIBLE, View.VISIBLE, View.GONE, View.VISIBLE, View.GONE});
                        return "对方拒绝代付";
                    } else if (order.getTradetype().equals("2")) {//不存在此状态
                        setBottomButton(new int[]{View.GONE, View.GONE, View.GONE, View.GONE, View.GONE, View.GONE});
                        return "对方已代付";
                    }else {//非代付
                        setBottomButton(new int[]{View.VISIBLE, View.VISIBLE, View.VISIBLE, View.GONE, View.VISIBLE, View.GONE});
                        return "待付款";
                    }
                }else if (order.getTradetype().equals("1")) {
                    setBottomButton(new int[]{View.GONE, View.GONE, View.GONE, View.GONE, View.GONE, View.GONE});
                    return "待发货";
                }else if (order.getTradetype().equals("2")) {
                    setBottomButton(new int[]{View.VISIBLE, View.GONE, View.GONE, View.GONE, View.GONE, View.VISIBLE});
                    return "待收货";
                }else if (order.getTradetype().equals("3")) {
                    setBottomButton(new int[]{View.GONE, View.GONE, View.GONE, View.GONE, View.GONE, View.GONE});
                    return "待评价";
                }else if (order.getTradetype().equals("4")) {
                    setBottomButton(new int[]{View.GONE, View.GONE, View.GONE, View.GONE, View.GONE, View.GONE});
                    return "交易成功";
                }else {
                    setBottomButton(new int[]{View.GONE, View.GONE, View.GONE, View.GONE, View.GONE, View.GONE});
                    return "未知状态";
                }
            }
        }

        /**
         * @param visibility
         * 依次为：底部按钮、取消订单、代付、拒绝、支付、确认收货、删除订单、评价
         */
        private void setBottomButton(int[] visibility) {
            layoutBottom.setVisibility(visibility[0]);
            divLine.setVisibility(visibility[0]);
            tvCancel.setVisibility(visibility[1]);
            tvFriendPay.setVisibility(visibility[2]);
            tvRefuse.setVisibility(visibility[3]);
            tvPay.setVisibility(visibility[4]);
            tvConfirm.setVisibility(visibility[5]);
            tvHint.setVisibility(View.GONE);
            tvCommit.setVisibility(View.GONE);
            tvAftersale.setVisibility(View.GONE);
        }

        private class ItemViewHolder {
            private ImageView img;
            private TextView name;
            private TextView price;
            private TextView amount;
            private TextView tvCommit;//复用Layout，这里的评论和申请售后，显示为“同意”“拒绝”
            private TextView tvAfterSale;
            private View div;
            private TextView tvHint;
            private TextView tvGoodsSpec;
        }

        /**
         * 一个订单中的多个商品
         *
         * @param view
         * @param ivHolder
         */
        private void itemFindView(View view, ItemViewHolder ivHolder) {
            ivHolder.img = (ImageView) view.findViewById(R.id.img);
            ivHolder.name = (TextView) view.findViewById(R.id.good_name);
            ivHolder.price = (TextView) view.findViewById(R.id.price);
            ivHolder.amount = (TextView) view.findViewById(R.id.count);
            ivHolder.tvCommit = (TextView) view.findViewById(R.id.tv_commit);
            ivHolder.tvAfterSale = (TextView) view.findViewById(R.id.tv_aftersale);
            ivHolder.div = view.findViewById(R.id.divider);
            ivHolder.tvHint = (TextView) view.findViewById(R.id.tv_hint);
            ivHolder.tvGoodsSpec = (TextView) view.findViewById(R.id.tv_goods_spec);
        }

        private void setItem(final int position, ViewHolder holder, int i, final Order bill,
                             View view, ItemViewHolder ivHolder) {
            final Order.BillChild child = bill.getChildren().get(i);
            ImageUtils.loadSmalImage(mContext, child.getImgurl(), ivHolder.img);
            ivHolder.name.setText(child.getName());
            ivHolder.price.setText("¥" + child.getPrice());
            ivHolder.amount.setText("x" + child.getBuycount());
            if (!TextUtils.isEmpty(child.getOne_specname())) {
                ivHolder.tvGoodsSpec.setVisibility(View.VISIBLE);
                StringBuffer spec = new StringBuffer(child.getOne_spec());
                spec.append(":").append(child.getOne_specname());
                if (!TextUtils.isEmpty(child.getTwo_specname())) {
                    spec.append("    ").append(child.getTwo_spec()).append(":").append(child.getTwo_specname());
                }
                ivHolder.tvGoodsSpec.setText(spec.toString());
            }else
                ivHolder.tvGoodsSpec.setVisibility(View.GONE);
            holder.layoutGoods.addView(view);
            if (i == bill.getChildren().size() - 1) {
                ivHolder.div.setVisibility(View.GONE);
            } else {
                ivHolder.div.setVisibility(View.VISIBLE);
            }
            //订单列表中，不显示商品的评价、售后信息，2016.10.12
            ivHolder.tvHint.setVisibility(View.GONE);
            ivHolder.tvCommit.setVisibility(View.GONE);
            ivHolder.tvAfterSale.setVisibility(View.GONE);
//            //显示订单列表中商品的评价、售后等提示信息
//            if (!bill.getClient_id().equals(BaseApplication.getInstance().getUser().getId())) {//别人请我帮忙代付
//                ivHolder.tvCommit.setVisibility(View.GONE);
//                ivHolder.tvAfterSale.setVisibility(View.GONE);
//            }else {
//                //判断是否已经评价
//                if (bill.getTradetype().equals("3")) {//如果订单未评价，那么再去判断订单中的商品有没有评价
//                    if (child.getReplytype().equals("0")) {//订单中的商品未评论，显示去评价
//                        ivHolder.tvCommit.setVisibility(View.VISIBLE);
//                    } else {
//                        ivHolder.tvCommit.setVisibility(View.GONE);
//                        ivHolder.tvHint.setVisibility(View.VISIBLE);
//                        ivHolder.tvHint.setText("已评价");
//                    }
//                }
//                //	0:未付款;1:已付款待发货;2:待收货;3:已收货待评价;4:已评价交易成功
//                if (bill.getTradetype().equals("1") || bill.getTradetype().equals("2") || (bill.getTradetype().equals("3") && child.getReplytype().equals("0"))) {
//                    if (child.getBlogReturnflag().equals("0")) {//允许退货标记:0不允许;1允许
//                        ivHolder.tvAfterSale.setVisibility(View.GONE);
//                        ivHolder.tvHint.setVisibility(View.VISIBLE);
//                        ivHolder.tvHint.setText("不支持退货");
//                    } else {
//                        String itemType = child.getItemtype();
//                        if (itemType.equals("0")) {//状态	0正常 1申请中 2等待买家发货 3拒绝 4退货中 5退货完成
//                            ivHolder.tvAfterSale.setVisibility(View.VISIBLE);
//                        }else if(itemType.equals("1")) {
//                            ivHolder.tvCommit.setVisibility(View.GONE);
//                            ivHolder.tvAfterSale.setVisibility(View.GONE);
//                            ivHolder.tvHint.setVisibility(View.VISIBLE);
//                            ivHolder.tvHint.setText("审核中");
//                        }else if(itemType.equals("2")) {
//                            ivHolder.tvCommit.setVisibility(View.GONE);
//                            ivHolder.tvAfterSale.setVisibility(View.GONE);
//                            ivHolder.tvHint.setVisibility(View.VISIBLE);
//                            ivHolder.tvHint.setText("待退货");
//                        }else if(itemType.equals("3")) {//退货失败，按照正常流程继续进行
//                            ivHolder.tvAfterSale.setVisibility(View.GONE);
//                            ivHolder.tvHint.setVisibility(View.VISIBLE);
//                            ivHolder.tvHint.setText("退货失败");
//                        }else if(itemType.equals("4")) {
//                            ivHolder.tvCommit.setVisibility(View.GONE);
//                            ivHolder.tvAfterSale.setVisibility(View.GONE);
//                            ivHolder.tvHint.setVisibility(View.VISIBLE);
//                            ivHolder.tvHint.setText("退货中");
//                        }else if(itemType.equals("5")) {
//                            ivHolder.tvCommit.setVisibility(View.GONE);
//                            ivHolder.tvAfterSale.setVisibility(View.GONE);
//                            ivHolder.tvHint.setVisibility(View.VISIBLE);
//                            ivHolder.tvHint.setText("退货成功");
//                        }else {
//                            ivHolder.tvCommit.setVisibility(View.GONE);
//                            ivHolder.tvAfterSale.setVisibility(View.GONE);
//                            ivHolder.tvHint.setVisibility(View.VISIBLE);
//                            ivHolder.tvHint.setText("退货中");
//                        }
//                    }
//                }else {
//                    ivHolder.tvAfterSale.setVisibility(View.GONE);
//                }
//            }
            ivHolder.tvCommit.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
//                    Intent itCommit = new Intent(mContext, CommentProductionActivity.class);
//                    itCommit.putExtra("goods_id", child.getBlog_id());
//                    mContext.startActivity(itCommit);
                }
            });
            ivHolder.tvAfterSale.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
//                    Intent itCommit = new Intent(mContext, ApplyAfterSalesActivity.class);
//                    itCommit.putExtra("goods", child);
//                    itCommit.putExtra("type", 1);
//                    itCommit.putExtra("recvdate", bill.getRecvdate());//确认收货时间
//                    mContext.startActivity(itCommit);
                }
            });
        }
    }
}
